const {query}= require('../util/query')

/*
获取用户总数
 */
let getTotal=async function(){
    let _sql=`SELECT COUNT(*) AS total FROM USER`
    let result = await query(_sql)
    return result[0]
}

/*
查询用户角色
 */
let findUserAndRole = async function(id) {
    let _sql = `
    SELECT u.*,r.NAME FROM AUTH_USER u,AUTH_USER_ROLE ur,AUTH_ROLE r where u.ID=(SELECT ID FROM AUTH_USER where ID=${id} limit 1) and ur.USER_ID=u.ID and r.ID=ur.ROLE_ID limit 1;
  `
    let result = await query(_sql)

    if (Array.isArray(result) && result.length > 0) {
        result = result[0]
    } else {
        result = null
    }
    return result
}
/*
记录用户行为
 */
let saveUserInfo = async function(value) {
    let _sql =
        'INSERT INTO AUTH_USER_BEHAVIOR set ?;'
    return query(_sql, value)
}

/*
分配用户至角色
 */
let allocateRole=async function(id,roleId){
    let _sql=
        `UPDATE AUTH_USER_ROLE SET ROLE_ID = '${roleId}' WHERE USER_ID = '${id}'`
    return query(_sql)
}
/*
通过id查找用户
 */
let findUserInfoById = async function(id) {
    let _sql = `
    SELECT ID, NICK_NAME, SEX, AVATAR, EMAIL, PHONE FROM USER WHERE ID='${id}' limit 1;
  `
    let result = await query(_sql)

    if (Array.isArray(result) && result.length > 0) {
        result = result[0]
    } else {
        result = null
    }
    return result
}
/*
通过id删除用户
 */
let deleteUserById=async function(id){
    let _sql=`
        DELETE FROM AUTH_USER_ROLE WHERE USER_ID = '${id}';
    `
    let _sql_user=`
        DELETE FROM USER WHERE ID = '${id}';
    `
    let result_role=await query(_sql)
    let result_user=await query(_sql_user)
    return Promise.all([result_role,result_user])
}

/*
用户注册
 */
let register = async function(value) {
  let _sql =
    `INSERT INTO staff set ?;`
  let result=await query(_sql,value[0])
  let _sql1=
    `INSERT INTO contract set ?;`
  let result_1=await query(_sql1,value[1])
  let _sql2=
    `INSERT INTO contract_detail set ?;`
  let result_2=await query(_sql2,value[2])
  return Promise.all([result,result_1,result_2])
}
/*
获取所有用户列表
 */
let getUserList=async function(page,pageNumber){{
  // let _sql=`SELECT * FROM USER,AUTH_USER_ROLE WHERE USER.ID=AUTH_USER_ROLE.USER_ID LIMIT ${page},${pageNumber};`
  let _sql=`SELECT * FROM staff`
  return await query(_sql)
}}
/*
用户是否存在
 */
let findUser=async function(id){
  let _sql=`SELECT * FROM staff where workNumber="${id}" limit 1;`
  let result=await query(_sql)
  if (Array.isArray(result) && result.length > 0) {
    result = result[0]
  } else {
    result = null
  }
  return result
}
module.exports = {
    getTotal,
    findUser,
    getUserList,
    findUserAndRole,
    saveUserInfo,
    findUserInfoById,
    register,
    deleteUserById,
    allocateRole
}

